import { Editor } from "@/editor";
import { BaseOpt } from "@/operations";
import KeyboardEventer from "./keyboard.event";

interface OptNode {
  data?: BaseOpt;
  pre?: OptNode;
  next?: OptNode;
}
let current : OptNode = {}
current.pre = current

export default function withHistory(editor: Editor): Editor {
  let commit = editor.commit.bind(editor)
  editor.commit = (opt: BaseOpt) => {
    if (!current.data || !current.data.merge(opt)) {
      let node = { data: opt, pre: current }
      current.next = node
      current = node
    } else {
      current.next = undefined
    }
    commit(opt)
  }
  editor.registeEventer(new KeyboardEventer(redo, undo))
  return editor
}

function redo() {
  if (!current || !current.next) return
  current = current.next
  current.data!.apply()
}
function undo() {
  current.data && current.data.reverse()
  current = current.pre!
}